package com.xnx3.kefu.admin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.SafetyUtil;
import com.xnx3.j2ee.util.SessionUtil;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.StringUtil;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.vo.UploadFileVO;
import com.xnx3.kefu.core.bean.ChatUserBean;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.entity.Zuoxi;
import com.xnx3.kefu.core.service.KefuService;
import com.xnx3.kefu.core.util.SocketUtil;
import com.xnx3.kefu.core.util.UserUtil;
import com.xnx3.kefu.core.vo.ZuoxiListVO;
import com.xnx3.kefu.core.vo.ZuoxiVO;
import com.xnx3.kefu.core.vo.bean.ZuoxiBean;

/**
 * 坐席设置
 * @author 管雷鸣
 */
@Controller(value="KefuZuoxiController")
@RequestMapping("/kefu/admin/zuoxi/")
public class ZuoxiController extends BaseController {
	@Autowired
	private SqlCacheService sqlCacheService;
	@Autowired
	private UserService userService;
	@Autowired
	private SqlService sqlService;
	@Autowired
	private KefuService kefuService;
	
	/**
	 * 坐席列表
	 */
	@ResponseBody
	@RequestMapping(value="/list.json", method = {RequestMethod.POST})
	public ZuoxiListVO list(HttpServletRequest request,Model model){
		ZuoxiListVO vo = new ZuoxiListVO();
		Kefu kefu = getKefu();
		
	    Sql sql = new Sql(request);
	    sql.appendWhere("kefu_zuoxi.kefuid = "+kefu.getId());
	    //查询user数据表的记录总条数。 传入的user：数据表的名字为user
	    int count = sqlService.count("kefu_zuoxi", sql.getWhere());
	    //创建分页，并设定每页显示15条
	    Page page = new Page(count, 15, request);
	    //创建查询语句，只有SELECT、FROM，原生sql查询。其他的where、limit等会自动拼接
	    sql.setSelectFromAndPage("SELECT user.*,kefu_zuoxi.id AS zuoxiid FROM user, kefu_zuoxi ", page);
	    sql.appendWhere("user.id = kefu_zuoxi.userid");
	    //因只查询的一个表，所以可以将查询结果转化为实体类，用List接收。
	    List<Map<String,Object>> list = sqlService.findMapBySql(sql);
	    
	    //组合返回的vo
	    List<ZuoxiBean> zuoxiBeanList = new ArrayList<ZuoxiBean>();	
	    for (int i = 0; i < list.size(); i++) {
	    	Map<String,Object> map = list.get(i);
			String zuoxiid = (String) map.get("zuoxiid");
			ChatUserBean chatUserBean = UserUtil.getUser(zuoxiid);
			
			ZuoxiBean bean = new ZuoxiBean();
			bean.setChatUserBean(chatUserBean);
			bean.setHead(userService.getHead((String) map.get("head")));
			bean.setNickname((String) map.get("nickname"));
			bean.setOnline(SocketUtil.getChannel(zuoxiid).size() > 0);
			zuoxiBeanList.add(bean);
		}
	    
	    vo.setList(zuoxiBeanList);
	    vo.setPage(page);
	    return vo;
	}
	

	/**
	 * 添加坐席
	 * @param username 登录坐席的用户名
	 * @param password 登录坐席的密码
	 * @param nickname 坐席的昵称
	 * @author 管雷鸣
	 */
	@ResponseBody
	@RequestMapping(value="/save${api.suffix}" ,method = {RequestMethod.POST})
	public com.xnx3.j2ee.vo.BaseVO save(HttpServletRequest request,
			@RequestParam(value = "username", required = false , defaultValue="") String username,
			@RequestParam(value = "password", required = false , defaultValue="") String password,
			@RequestParam(value = "nickname", required = false , defaultValue="") String nickname) {
		Kefu kefu = getKefu();	//当前登录的客服平台
		
		BaseVO vo = kefuService.createZuoxi(request, username, password, nickname, kefu);
		if(vo.getResult() - BaseVO.SUCCESS == 0){
			//成功。日志记录
			ActionLogUtil.insertUpdateDatabase(request, "增加坐席", "zuoxiid:"+vo.getInfo()+", username:"+SafetyUtil.xssFilter(username));
		}
		
		return vo;
	}
	

	/**
	 * 删除客服坐席。这里为了省事直接物理删除
	 * @param zuoxiid 要删除的坐席的id，也就是 zuoxi.id
	 */
	@RequestMapping(value="delete${api.suffix}", method = {RequestMethod.POST})
	@ResponseBody
	public BaseVO delete(HttpServletRequest request,
			@RequestParam(value = "zuoxiid", required = false , defaultValue="") String zuoxiid){
		Kefu kefu = getKefu();	//当前登录的客服平台
		
		if(zuoxiid.length() < 1){
			return error("请输入zuoxiid");
		}
		//权限验证，只有当前客服平台拥有者才能操作
		if(kefu.getUserid() - getUserId() != 0){
			return error("非客服平台管理者，无法操作。");
		}
		
		//删除zuoxi
		Zuoxi zuoxi = sqlService.findById(Zuoxi.class, zuoxiid);
		
		//判断要删除的坐席是否是当前客服平台本人，如果是，不允许删除
		if(kefu.getUserid() - zuoxi.getUserid() == 0) {
			return error("客服平台的管理者本人无法被删除");
		}
		
		if(zuoxi == null){
			return error("要删除的坐席不存在");
		}
		sqlService.delete(zuoxi);
		
		//删除 user
		User user = sqlService.findById(User.class, zuoxi.getUserid());
//		user.setIsfreeze(User.ISFREEZE_FREEZE);
//		sqlService.save(user);
		sqlService.delete(user);
	
		//日志
		ActionLogUtil.insert(request,getKefuId(), "删除客服坐席", zuoxi.toString());
		return success();
	}
	
	

	/**
	 * 获取坐席信息，通过这个坐席的userid 
	 * @param userid 也就是 zuoxi.userid
	 */
	@ResponseBody
	@RequestMapping("getZuoxiByUserid${api.suffix}")
	public ZuoxiVO getZuoxiByUserid(HttpServletRequest request,
			@RequestParam(value = "userid", required = false , defaultValue="0") int userid){
		ZuoxiVO vo = new ZuoxiVO();
		
		Zuoxi zuoxi = sqlCacheService.findAloneByProperty(Zuoxi.class, "userid", userid);
//		Zuoxi zuoxi = sqlService.findAloneByProperty(Zuoxi.class, "userid", userid);
		if(zuoxi == null){
			vo.setBaseVO(BaseVO.FAILURE, "坐席不存在");
			return vo;
		}
		
		User user = sqlCacheService.findById(User.class, userid);
//		User user = sqlService.findById(User.class, userid);
		if(user == null){
			vo.setBaseVO(BaseVO.FAILURE, "用户不存在");
			return vo;
		}
		vo.setHead(userService.getHead(user));
		vo.setId(zuoxi.getId());
		vo.setNickname(user.getNickname());
		
		ActionLogUtil.insert(request,user.getId(), "获取坐席信息", vo.toString());
		return vo;
	}
	

	/**
	 * 客服名字修改
	 * @param request 需post/get传入nickname 客服的名字，即user.nickname，不可为空。
	 */
	@RequestMapping("updateNickname${api.suffix}")
	@ResponseBody
	public BaseVO updateNickname(HttpServletRequest request){
		User user = getUser();
		BaseVO vo = userService.updateNickname(request);
		if(vo.getResult() - BaseVO.SUCCESS == 0){
			//成功
			//清理缓存
			sqlCacheService.deleteCacheById(User.class, user.getId());
			//日志
			ActionLogUtil.insert(request,getKefuId(), "客服名字修改", SafetyUtil.filter(getUser().getNickname()));
		}
		return vo;
	}
	

	/**
	 * 当前客服的属性保存，更新客服的头像
	 * @param head 上传的头像文件
	 */
	@RequestMapping(value="updateHead.json", method = {RequestMethod.POST})
	@ResponseBody
	public UploadFileVO updateHead(HttpServletRequest request, @RequestParam("head") MultipartFile head){
		UploadFileVO vo = userService.updateHead(head);
		User user = getUser();
		if(vo.getResult() - UploadFileVO.SUCCESS == 0){
			//成功
			//清理缓存
			sqlCacheService.deleteCacheById(User.class, user.getId());
			//日志
			ActionLogUtil.insert(request, getKefuId(), "更新客服的头像", vo.getUrl());
		}
		return vo;
	}
	
}
